//
//  CTDialViewController.m
//  CT
//
//  Created by liufanwei on 15/3/13.
//  Copyright (c) 2015年 liufanwei. All rights reserved.
//

#import "CTDialViewController.h"
#import "CTDialTableViewCell.h"
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
#import "CommonMicro.h"
#import "UILabel+WBExtension.h"
#import "UIView+MJExtension.h"
#import "UIView+WBExtension.h"
#import "CTNetHelper.h"
#import "CTUserDefaultHelper.h"
#import "BDKNotifyHUD.h"
#import "CTDialKeyboard.h"
#import "CTCallViewController.h"
#import "CTDataManager.h"

@interface CTDialViewController ()<UITextFieldDelegate,
                                    CTDialKeyboardDelegate,
                                    ABNewPersonViewControllerDelegate,
                                    UIAlertViewDelegate>
{
    UILabel     * _PriceLabel;
    NSMutableArray * _Data;
    CTDialKeyboard * _DialKeyboard;
    CTContactShowItem * _SelectItem;
}

@end

@implementation CTDialViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barTintColor = kBackGroundColor;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIButton *rightBg = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 84, 34)];
    [rightBg addTarget:self action:@selector(onRefreshMoney:) forControlEvents:UIControlEventTouchUpInside];
    rightBg.backgroundColor = kBackGroundColor;
    rightBg.clipsToBounds = YES;
    rightBg.layer.borderColor = [UIColor whiteColor].CGColor;
    rightBg.layer.borderWidth = 2.0f;
    
    UIImage * image = [UIImage imageNamed:@"coin"];
    UIImageView * imageview = [[UIImageView alloc] initWithImage:image];
    imageview.frame = CGRectMake(0, 0, 25, 23);
    [imageview setPosition:CGPointMake(3, CGRectGetMidY(rightBg.frame) - CGRectGetMidY(imageview.frame))];
    
    NSString * money = [[CTUserDefaultHelper ShareInstance] Money];
    if (!money) {
        money = @"0";
    }
    money = [NSString stringWithFormat:@"%@",money];
    _PriceLabel = [UILabel labelWithText:money font:[UIFont fontWithName:kFontName size:18]];
    CGRect priceRect = _PriceLabel.frame;
    priceRect.size.width = rightBg.frame.size.width;
    _PriceLabel.frame = priceRect;
    _PriceLabel.numberOfLines = 2;
    _PriceLabel.textColor = [UIColor whiteColor];
    [_PriceLabel setPosition:CGPointMake(CGRectGetWidth(imageview.frame)+4, 4)];
    [rightBg addSubview:imageview];
    [rightBg addSubview:_PriceLabel];
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:rightBg];
    self.navigationItem.rightBarButtonItem = item;
    
    UIButton * cleanButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 34)];
    [cleanButton setTitle:@"清空记录" forState:UIControlStateNormal];
    cleanButton.backgroundColor = kBackGroundColor;
    cleanButton.clipsToBounds = YES;
    cleanButton.layer.borderColor = [UIColor whiteColor].CGColor;
    cleanButton.layer.borderWidth = 2.0;
    [cleanButton addTarget:self action:@selector(onCleanHistory:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:cleanButton];
    self.navigationItem.leftBarButtonItem = leftItem;
    [self onRefreshMoney:Nil];
    
    _Data = [[NSMutableArray alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNotification:) name:kNotifiCationLoadContactsReply object:Nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotifiCationLoadContactsReply object:Nil];
}

-(void)onNotification:(NSNotification*)sender{
    if ([sender.name isEqualToString:kNotifiCationLoadContactsReply]) {
        _Data = [[[CTDataManager shareInstance] HistoryManager] allHistory];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }else{
        NSString * str = sender.object;
        BOOL b = [str boolValue];
        if (b) {
            NSArray * arr = [[NSBundle mainBundle] loadNibNamed:@"DialKeyboard" owner:self options:Nil];
            _DialKeyboard = [arr objectAtIndex:0];
            CGRect rect = self.view.frame;
            _DialKeyboard.frame = rect;
            _DialKeyboard.delegate = self;
            [kAppWindow addSubview:_DialKeyboard];
        }else{
            [_DialKeyboard removeFromSuperview];
        }
    }
}

-(void)onCleanHistory:(NSNotification*)sender
{
    UIAlertView * alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否清除所有通讯记录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alertview show];
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [[[CTDataManager shareInstance] HistoryManager] cleanHistory];
        [_Data removeAllObjects];
        [self.tableView reloadData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNotification:) name:kNotifiCationShowKeyboard  object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNotification:) name:kNotifiCationHidKeyboard  object:Nil];
    _Data = [[[CTDataManager shareInstance] HistoryManager] allHistory];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotifiCationShowKeyboard object:Nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotifiCationHidKeyboard object:Nil];
    [super viewDidDisappear:animated];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _Data.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTContactShowItem * item = [_Data objectAtIndex:indexPath.row];
    NSString * idetifier = @"dialTableViewCell";
    CTDialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idetifier forIndexPath:indexPath];
    [cell setdata:item];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _SelectItem = [_Data objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:@"makecall1" sender:self];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(void)onRefreshMoney:(id)sender{
    NSString * account = [[CTUserDefaultHelper ShareInstance] Account];
    [[CTNetHelper ShareInstance] remainingMoney:@{@"account":account} WithCallBack:^(id data) {
        NSString * money = [data objectForKey:@"money"];
        _PriceLabel.text = [NSString stringWithFormat:@"%@",money];
        if ([[data objectForKey:@"code"] integerValue] == 0) {
            [[CTUserDefaultHelper ShareInstance] setMoney:money];
        }
        [BDKNotifyHUD notifyHUDWithText:[data objectForKey:@"msg"]];
    }];
}

-(void)onCallClicked:(NSString *)number{
    _SelectItem = [CTContactShowItem create];
    _SelectItem.PhoneNumber = number;
    [self performSegueWithIdentifier:@"makecall1" sender:self];
}

-(void)onSaveClicked:(NSString *)number{
    if (number == Nil || number.length == 0) {
        return;
    }
    ABNewPersonViewController * _NewPersonVC = [[ABNewPersonViewController alloc] init];
    _NewPersonVC.newPersonViewDelegate = self;
    _NewPersonVC.hidesBottomBarWhenPushed = YES;
    
    ABRecordRef newPerson = ABPersonCreate();
    ABMutableMultiValueRef multiValue = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
    CFErrorRef error = NULL;
    multiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(multiValue, (__bridge CFTypeRef)number, kABPersonPhoneMainLabel, NULL);
    ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiValue , &error);
    _NewPersonVC.displayedPerson = newPerson;
    [self.navigationController pushViewController:_NewPersonVC animated:YES];
}

-(void)onTextChanged:(NSString *)text{
    if(text.length == 0){
        _Data = [[[CTDataManager shareInstance] HistoryManager] allHistory];
    }else{
        _Data = [[[CTDataManager shareInstance] HistoryManager] allFiltrate:text];
    }
    [self.tableView reloadData];
}



- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person{
    [self.navigationController popViewControllerAnimated:TRUE];
    if(person){
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotifiCationLoadContactsRequest object:Nil];
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        CTContactShowItem * item = [_Data objectAtIndex:indexPath.row];
        [[[CTDataManager shareInstance] HistoryManager] removeItem:item];
        [_Data removeObject:item];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    CTCallViewController * dest = segue.destinationViewController;
    dest.ItemData = _SelectItem;
}


@end
